// Copyright (c) 2022 CHANGLEI. All rights reserved.

import 'package:aircraft_war/bloc/bloc_listenable.dart';
import 'package:aircraft_war/bloc/game_firepower_cubit.dart';
import 'package:aircraft_war/commons/fonts.dart';
import 'package:aircraft_war/components/enemy_aircraft.dart';
import 'package:aircraft_war/components/game_console.dart';
import 'package:aircraft_war/components/main_game.dart';
import 'package:aircraft_war/generated/assets.dart';
import 'package:flame/components.dart';
import 'package:flame/extensions.dart';
import 'package:flame/flame.dart';
import 'package:flame/input.dart';
import 'package:flutter/cupertino.dart';

final _sprite = Sprite(Flame.images.fromCache(Images.bomb));
final _spriteSize = Vector2(30 * 63 / 57, 30);
final _textPaint = TextPaint(
  style: const TextStyle(
    color: CupertinoColors.label,
    fontSize: 20,
    fontWeight: FontWeight.w500,
    fontFamily: handwritten,
  ),
);

/// Created by changlei on 2022/5/18.
///
/// 火力值
class FirepowerValue extends PositionComponent
    with BlocListenable<GameFirepowerCubit, int>, HasGameRef<MainGame>, Tappable {
  int? _value;
  Vector2? _parentSize;

  /// 设置值
  set value(int value) {
    if (_value == value) {
      return;
    }
    _value = value;
    if (_parentSize != null) {
      layout(_parentSize!);
    }
  }

  @override
  Future<void> onLoad() async {
    onNewState(gameRef.firepowerCubit.state);
  }

  @override
  void render(Canvas canvas) {
    if (gameRef.firepowerCubit.isMin) {
      return;
    }
    _sprite.render(
      canvas,
      size: _spriteSize,
    );
    if (_value != null) {
      _textPaint.render(canvas, 'x $_value', Vector2(_spriteSize.x + 10, 0));
    }
  }

  /// 布局
  void layout(Vector2 parentSize) {
    _parentSize = parentSize;
    if (!isMounted || gameRef.firepowerCubit.isMin) {
      size = Vector2.zero();
    } else {
      size = Vector2(_spriteSize.x, 30);
      if (_value != null) {
        size += Vector2(_textPaint.measureTextWidth('x $_value') + 10, 0);
      }
    }
    position = Vector2(20, parentSize.y - 20 - size.y);
  }

  @override
  void onNewState(int state) {
    value = state;
  }

  @override
  bool onTapDown(TapDownInfo info) {
    if (gameRef.firepowerCubit.isMin || !gameRef.isRunning) {
      return true;
    }
    gameRef.firepowerCubit.consume();

    GameConsole? console;
    void where(Component component) {
      if (component is GameConsole) {
        console = component;
      } else {
        component.children.forEach(where);
      }
    }

    gameRef.children.forEach(where);

    if (console == null) {
      return true;
    }

    for (var element in console!.children.whereType<EnemyAircraft>()) {
      element.destroy();
    }
    return false;
  }
}
